package com.jdcjk.project.login.view;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jdcjk.Constant;
import com.jdcjk.R;
import com.jdcjk.UrlAddress;
import com.jdcjk.base.presenter.BasePresenter;
import com.jdcjk.base.view.BaseActivity;
import com.jdcjk.project.account.view.AccountActivity;
import com.jdcjk.project.login.model.entity.LoginResult;
import com.jdcjk.project.login.presenter.LoginPresenter;
import com.jdcjk.project.main.view.MainActivity;
import com.jdcjk.util.PreferencesUtils;
import com.jdcjk.view.LoadingDialog;

import java.util.HashMap;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Request;

import static com.jdcjk.R.id.login_number_et;

/**
 * Created by Administrator on 2016/12/13 0013.
 * 登录界面
 */
public class LoginActivity extends BaseActivity<LoginPresenter> implements View.OnClickListener {
    private final String TAG = LoginActivity.class.getSimpleName();
    // 账户名EditText
    private EditText loginNum_editText;
    // 登录密码EditText
    private EditText loginPwd_editText;
    // 忘记密码Textview
    private TextView forgetPwd_TextView;
    // 登录Button
    private Button login_button;
    // 试用Textview
    private TextView userTry_TextView;
    // 新用户注册Textview
    private TextView newUserRegistered_TextView;
    private LoginPresenter loginPresenter;

    private LoadingDialog loadingDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public LoginPresenter bindPresenter() {
        loginPresenter = new LoginPresenter(getBaseContext());
        return loginPresenter;
    }

    @Override
    public void initContentView(Bundle savedInstanceState) {
        loginNum_editText = (EditText) findViewById(login_number_et);
        loginPwd_editText = (EditText) findViewById(R.id.login_pwd_et);
        forgetPwd_TextView = (TextView) findViewById(R.id.forget_pwd_tv);
        forgetPwd_TextView.setOnClickListener(this);
        login_button = (Button) findViewById(R.id.login_btn);
        login_button.setOnClickListener(this);
        newUserRegistered_TextView = (TextView) findViewById(R.id.new_user_registered_tv);
        newUserRegistered_TextView.setOnClickListener(this);
        //初始化加载dialog
        loadingDialog = new LoadingDialog(this, R.style.dialogTheme);
        loadingDialog.setTextView(getResources().getString(R.string.is_login));
    }

    @Override
    public void initData() {
        super.initData();
        //如果有存在的账号，则设置登录账号为该账号
        if (PreferencesUtils.getString(this, Constant.UserInfo.account) != "")
            loginNum_editText.setText(PreferencesUtils.getString(this, Constant.UserInfo.account));
    }

    @Override
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            //忘记密码监听
            case R.id.forget_pwd_tv:
                intent = new Intent(this, AccountActivity.class);
                //设置需要弹出的界面（registered为注册界面，retrievePwd为找回密码界面）
                intent.putExtra(Constant.FragmentInfo.fragment, Constant.FragmentInfo.retrievePwd);
                startActivity(intent);
                break;
            //登录按钮监听
            case R.id.login_btn:
                //获得账号密码
                String loginNumber = loginNum_editText.getText().toString();
                String loginPwd = loginPwd_editText.getText().toString();
                if (!loginNumber.equals("") && !loginPwd.equals("")) {
                    login(loginNumber, loginPwd);
                } else {
                    Toast.makeText(this, "账号密码不能为空", Toast.LENGTH_SHORT).show();
                }
                break;
            // 新用户注册监听
            case R.id.new_user_registered_tv:
                intent = new Intent(this, AccountActivity.class);
                //设置需要弹出的界面（registered为注册界面，retrievePwd为找回密码界面）
                intent.putExtra(Constant.FragmentInfo.fragment, Constant.FragmentInfo.registered);
                startActivity(intent);
                break;
        }
    }

    private void login(final String account, final String passward) {
        loginPresenter.login(UrlAddress.LOGIN, account, passward, new BasePresenter.OnUIThreadListener<LoginResult>() {
            @Override
            public void onBefore(Request request, int id) {
                loadingDialog.show();
            }

            @Override
            public void onAfter(int id) {

            }

            @Override
            public void onError(Call call, Exception e, int i) {
                loadingDialog.dismiss();
                Toast.makeText(LoginActivity.this, R.string.request_failed, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(LoginResult result) {
                //如果登录成功,将登陆账号和密码保存在SharedPreferences
                switch (result.getStatus()) {
                    case "OK":
                        Map map = new HashMap();
                        //如果登录成功,将用户信息保存在SharedPreferences
                        map.put(Constant.UserInfo.account, account);
                        map.put(Constant.UserInfo.passward, passward);
                        map.put(Constant.UserInfo.username, result.getResult().getUsername());
                        map.put(Constant.UserInfo.email, result.getResult().getEmail());
                        map.put(Constant.UserInfo.address, result.getResult().getAddress());
                        map.put(Constant.UserInfo.id, result.getResult().getId());
                        map.put(Constant.UserInfo.phone, result.getResult().getAccount());
                        PreferencesUtils.saveData(LoginActivity.this, map);
                        // 跳转到主界面
                        Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                        startActivity(intent);
                        finish();
                        break;
                    case "FAILED":
                        loginPwd_editText.setText("");
                        Toast.makeText(LoginActivity.this, R.string.login_failed, Toast.LENGTH_SHORT).show();
                        break;
                    case "NOT_EXIST":
                        loginPwd_editText.setText("");
                        loginNum_editText.setText("");
                        Toast.makeText(LoginActivity.this, R.string.login_not_exist, Toast.LENGTH_SHORT).show();
                        break;
                    default:
                        Toast.makeText(LoginActivity.this, R.string.login_not_exception, Toast.LENGTH_SHORT).show();
                        break;
                }
                loadingDialog.dismiss();
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        refreshView();
    }


}
